# py module

from sys import *
from turnited._config import *

from turnited.page._base import TurnitedPageBase
from turnited.model.team import TeamModel
from turnited.model.liga import LigaModel

import wsgiref.handlers
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

from google.appengine.ext.db import djangoforms
from google.appengine.api import datastore_errors
from django import newforms as forms

######################################################################

class TeamForm(djangoforms.ModelForm):
    class Meta:
        model = TeamModel
    def clean_name(self):
        for k, v in self.__dict__.items():
            print >>stderr, "  XCV  %30s:'%s'" % (k, v)
        data = self.clean_data['name']
        if len(data) < 5: raise forms.ValidationError(u"Ein Teamname muss mindestens 5 Zeichen haben.")
        tq = TeamModel.all()
        tq.filter('name = ', data)
        if self.is_bound: # edit
            oldkey = self.data[u'key']
            tq.filter('__key__ !=', db.Key(oldkey)) # is there another object with this name?
        if tq.count(limit=1) > 0:
            raise forms.ValidationError(u"Ein Team mit diesem Namen existiert schon.")
        return data

######################################################################

class TeamNew(TurnitedPageBase):
    def get(self):
        self._commonRender(BASE_THTML + '/team_req.html', { 'form':TeamForm(), 'action':'team_new', 'key':'' } )

    def post(self):
        data = TeamForm(data = self.request.POST)
        if data.is_valid():
            entity = data.save(commit=False)
            entity.user = users.get_current_user()
            entity.put()
            self.redirect(BASE_REQ_ADMIN + '/team_list?msg=Team+neu+angelegt')
        else:
            self._commonRender(BASE_THTML + '/team_req.html', { 'form':data, 'action':'team_new', 'key':'' } )

class TeamEdit(TurnitedPageBase):
    def get(self):
        key = self.request.get('key')
        entry = TeamModel.get(db.Key(key))
        isDelete = self.request.get('del')
        if isDelete:
            entry.delete()
            self.redirect(BASE_REQ_ADMIN + '/team_list?msg=Team+entfernt')
        else:
            self._commonRender(BASE_THTML + '/team_req.html', { 'form':TeamForm(instance=entry), 'action':'team_edit', 'key':key } )

    def post(self):
        key = self.request.get('key')
        entry = TeamModel.get(db.Key(key))
        data = TeamForm(data=self.request.POST, instance=entry)
        if data.is_valid():
            entity = data.save(commit=False)
            entity.put()
            self.redirect(BASE_REQ_ADMIN + '/team_list?msg=Team+bearbeitet')
        else:
            self._commonRender(BASE_THTML + '/team_req.html', { 'form':data, 'action':'team_edit', 'key':key } )


class TeamList(TurnitedPageBase):
    def get(self):
        query = TeamModel.all().order('name')
        entries = [ r for r in query.fetch(limit=100) ]
        for tm in entries:
            try:
                tm.x_liga = tm.liga.name
                tm.valid = True
            except datastore_errors.Error:
                tm.x_liga = "-"
                tm.valid = False
        template_values = {
            'entries': entries,
            'error': self.request.get('error'),
            'msg': self.request.get('msg'),
            }
        self._commonRender(BASE_THTML + '/team_list.html', template_values)

